@file:JvmName("ImageUtils")
package root.electronclass.electronclass.ext

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.media.ThumbnailUtils
import android.provider.MediaStore
import android.widget.ImageView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
import kotlin.math.roundToInt

/**
 *
 * @author Lokiy
 * @date 2023/4/1 09:57
 */


/**
 * 加载网络图片
 */
fun ImageView.setVideoThumbnail(filePath: String?, kind: Int = MediaStore.Images.Thumbnails.MINI_KIND) {
    filePath ?: return
    val context = context
//    if (context is AppCompatActivity) {
    GlobalScope.launch(Dispatchers.Main + CoroutineExceptionHandler { }) {
        val bitmap: Bitmap? = withContext(Dispatchers.IO) {
            var bitmap: Bitmap? = null
            val retriever = MediaMetadataRetriever()
            try {
                if (filePath.startsWith("http://") || filePath.startsWith("https://") || filePath.startsWith("widevine://")) {
                    retriever.setDataSource(filePath, Hashtable())
                } else {
                    retriever.setDataSource(filePath)
                }
                bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC) //retriever.getFrameAtTime(-1);
            } catch (ex: IllegalArgumentException) {
// Assume this is a corrupt video file
                ex.printStackTrace()
            } catch (ex: RuntimeException) {
// Assume this is a corrupt video file.
                ex.printStackTrace()
            } finally {
                try {
                    retriever.release()
                } catch (ex: RuntimeException) {
// Ignore failures while cleaning up.
                    ex.printStackTrace()
                }
            }
            bitmap ?: return@withContext null
            if (kind == MediaStore.Images.Thumbnails.MINI_KIND) { //压缩图片 开始处
// Scale down the bitmap if it's too large.
                val width: Int = bitmap.width
                val height: Int = bitmap.height
                val max = width.coerceAtLeast(height)
                if (max > 512) {
                    val scale = 512f / max
                    val w = (scale * width).roundToInt()
                    val h = (scale * height).roundToInt()
                    bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true)
                } //压缩图片 结束处
            } else if (kind == MediaStore.Images.Thumbnails.MICRO_KIND) {
                bitmap = ThumbnailUtils.extractThumbnail(bitmap, 96, 96, ThumbnailUtils.OPTIONS_RECYCLE_INPUT)
            }
            bitmap
        }

        bitmap ?: return@launch

        setImageBitmap(bitmap)
    }
//    }
}
